import { _decorator, Component, Node, Vec2, Vec3, Sprite, UITransform, input, Input, EventTouch, tween, log } from 'cc';
import { GridMapManager } from './GridMapManager';
const { ccclass, property } = _decorator;

@ccclass('PathFollower')
export class PathFollower extends Component {
    @property(GridMapManager)
    gridMapManager: GridMapManager = null;

    @property
    moveSpeed: number = 200; // 移动速度，单位：像素/秒

    private _currentPath: Vec2[] = null;
    private _isMoving: boolean = false;
    private _currentPathIndex: number = 0;
    private _currentTween: any = null;

    start() {
        // 注册触摸事件
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
    }

    onDestroy() {
        // 取消注册触摸事件
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
    }

    onTouchStart(event: EventTouch) {
        if (this._isMoving) {
            // 如果正在移动，停止当前移动
            this.stopCurrentMovement();
        }

        // 获取触摸点的世界坐标
        const touchPos = event.getUILocation();
        const worldPos = new Vec2(touchPos.x, touchPos.y);

        // 获取当前Sprite的位置
        const startPos = new Vec2(this.node.position.x, this.node.position.y);

        // 寻找路径
        const path = this.gridMapManager.findPath(startPos, worldPos);

        for(let i = 0; i < path.length; i++){
            log(`path[${i}] = (${path[i].x}, ${path[i].y})`);
        }
        
        if (path && path.length > 0) {
            // 保存路径并开始移动
            this._currentPath = path;
            this._currentPathIndex = 0;
            this._isMoving = true;
            log(`Path found with ${path.length} points`);
            
            // 开始移动
            this.moveToNextPoint();
        } else {
            log("No valid path found");
        }
    }

    stopCurrentMovement() {
        this._isMoving = false;
        this._currentPath = null;
        this._currentPathIndex = 0;
        
        // 如果有正在进行的tween动画，停止它
        if (this._currentTween) {
            this._currentTween.stop();
            this._currentTween = null;
        }
    }

    moveToNextPoint() {
        if (!this._isMoving || !this._currentPath || this._currentPathIndex >= this._currentPath.length) {
            this._isMoving = false;
            this._currentTween = null;
            return;
        }

        // 获取当前位置和目标位置
        const currentPos = new Vec2(this.node.position.x, this.node.position.y);
        const targetPos = this._currentPath[this._currentPathIndex];

        // 计算这一段的距离和时间
        const distance = Vec2.distance(currentPos, targetPos);
        const duration = distance / this.moveSpeed;

        log(`Moving to point ${this._currentPathIndex + 1}/${this._currentPath.length} at (${targetPos.x}, ${targetPos.y})`);

        // 使用tween移动到下一个点
        this._currentTween = tween(this.node)
            .to(duration, {
                position: new Vec3(targetPos.x, targetPos.y, 0)
            }, {
                easing: 'linear' // 使用线性插值确保匀速运动
            })
            .call(() => {
                // 这一段移动完成
                this._currentPathIndex++;
                
                if (this._currentPathIndex < this._currentPath.length) {
                    // 还有下一个点，继续移动
                    this.moveToNextPoint();
                } else {
                    // 路径完成
                    this._isMoving = false;
                    this._currentTween = null;
                    log("Path movement completed");
                }
            })
            .start();
    }
}